package com.zxl.grocerymicroservicewechatmeal.service.impl;

import com.zxl.grocerymicroservicewechatmeal.dataobject.ProductInfo;
import com.zxl.grocerymicroservicewechatmeal.dto.CartDTO;
import com.zxl.grocerymicroservicewechatmeal.enums.ProductStatusEnum;
import com.zxl.grocerymicroservicewechatmeal.enums.ResultEnum;
import com.zxl.grocerymicroservicewechatmeal.exception.SellException;
import com.zxl.grocerymicroservicewechatmeal.repository.ProductInfoRepository;
import com.zxl.grocerymicroservicewechatmeal.service.ProductInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Author: zxl
 * @Description:
 * @Date: Created in 12:31 2017/11/15
 * @Modified By:
 */
@Service
//@CacheConfig(cacheNames = "productInfo")
public class ProductInfoServiceImpl implements ProductInfoService {
    @Autowired
    private ProductInfoRepository productInfoRepository;

//    @Autowired
//    private RedisLock redisLock;
//
//    private static final int TIMEOUT = 10 * 1000; //超时时间 10s

    @Override
    @Cacheable(cacheNames = "productInfo", key = "12452451")//key如果不填或者填空，那key默认为方法的参数（例如productId）
//    @Cacheable(key = "12452451")//key如果不填或者填空，那key默认为方法的参数（例如productId）
    public ProductInfo findOne(String productId) {
        return productInfoRepository.findOne(productId);
    }

    @Override
    public List<ProductInfo> findUpAll() {
        return productInfoRepository.findByProductStatus(ProductStatusEnum.UP.getCode());
    }

    @Override
    public Page<ProductInfo> findAll(Pageable pageable) {
        return productInfoRepository.findAll(pageable);
    }

    @Override
    @CachePut(cacheNames = "productInfo", key = "12452451")
//    @CachePut(key = "12452451")
    public ProductInfo save(ProductInfo productInfo) {
        return productInfoRepository.save(productInfo);
    }

    @Override
    @Transactional
    public void increaseStock(List<CartDTO> cartDTOList) {
        for (CartDTO cartDTO: cartDTOList) {
            ProductInfo productInfo = productInfoRepository.findOne(cartDTO.getProductId());
            if (productInfo == null) {
                throw new SellException(ResultEnum.PRODUCT_NOT_EXIST);
            }
            Integer result = productInfo.getProductStock() + cartDTO.getProductQuantity();
            productInfo.setProductStock(result);

            productInfoRepository.save(productInfo);
        }

    }

    @Override
    @Transactional
    public void decreaseStock(List<CartDTO> cartDTOList) {
        for (CartDTO cartDTO: cartDTOList) {
            //加锁
//            long time = System.currentTimeMillis() + TIMEOUT;
//            if (!redisLock.lock(cartDTO.getProductId(),String.valueOf(time))) {
//                throw new SellException(101,"人太多了，换个姿势再来一次^-^");
//            }

            ProductInfo productInfo = productInfoRepository.findOne(cartDTO.getProductId());
            if (productInfo == null) {
                throw new SellException(ResultEnum.PRODUCT_NOT_EXIST);
            }

            Integer result = productInfo.getProductStock() - cartDTO.getProductQuantity();
            if (result < 0) {
                throw new SellException(ResultEnum.PRODUCT_STOCK_ERROR);
            }

            productInfo.setProductStock(result);

            productInfoRepository.save(productInfo);

            //解锁
//            redisLock.unlock(cartDTO.getProductId(),String.valueOf(time));
        }
    }

    @Override
    public ProductInfo onSale(String productId) {
        ProductInfo productInfo = productInfoRepository.findOne(productId);
        if (productInfo == null) {
            throw new SellException(ResultEnum.PRODUCT_NOT_EXIST);
        }
        if (productInfo.getProductStatusEnum() == ProductStatusEnum.UP) {
            throw new SellException(ResultEnum.PRODUCT_STATUS_ERROR);
        }

        //更新
        productInfo.setProductStatus(ProductStatusEnum.UP.getCode());
        return productInfoRepository.save(productInfo);
    }

    @Override
    public ProductInfo offSale(String productId) {
        ProductInfo productInfo = productInfoRepository.findOne(productId);
        if (productInfo == null) {
            throw new SellException(ResultEnum.PRODUCT_NOT_EXIST);
        }
        if (productInfo.getProductStatusEnum() == ProductStatusEnum.DOWN) {
            throw new SellException(ResultEnum.PRODUCT_STATUS_ERROR);
        }

        //更新
        productInfo.setProductStatus(ProductStatusEnum.DOWN.getCode());
        return productInfoRepository.save(productInfo);
    }
}
